﻿#include "server.h"
#include<QMessageBox>
#include<QDebug>
#include<QJsonDocument>
#include "DataBase/mysql.h"
#include "constant.h"
Server::Server(QObject *parent,int port)
    :QTcpServer(parent)
{
    Q_UNUSED(port);
    listen(QHostAddress::Any,8889);
}

Server * Server::m_instance = NULL;
Server *Server::instance()
{
    if (NULL == m_instance)
    {
        m_instance = new Server();
    }

    return m_instance;
}

Server *Server::getInstance()
{
    return instance();
}

void Server::returnDatatoDistach(int sptr,QJsonObject json)
{
    emit updateMsg(json);
    emit writeMsg(sptr,json);
}



void Server::incomingConnection(qintptr socketDescriptor)
{
    qDebug()<<"new connection"<<socketDescriptor;
    DispatcherThread *cThread = new DispatcherThread;
    cThread->setSocketDescriptor(socketDescriptor);
    connect(cThread,SIGNAL(closeMe(DispatcherThread*)),this,SLOT(deleteClientThread(DispatcherThread*)),Qt::QueuedConnection);
    connect(cThread,SIGNAL(updateMsg(QString,QString)),this,SLOT(updateMessage(QString,QString)),Qt::QueuedConnection);

    connect(cThread,SIGNAL(updateMsg(QJsonObject)),this,SLOT(updateMessage(QJsonObject)),Qt::QueuedConnection);
    connect(this,SIGNAL(writeMsg(int,QJsonObject)),cThread,SLOT(writeData(int,QJsonObject)),Qt::QueuedConnection);//向客户端发送指令
    connect(cThread,SIGNAL(updateClient(QString)),this,SLOT(updateClients(QString)),Qt::QueuedConnection);
    m_threadList.append(cThread);
    cThread->start();
}


void Server::updateMessage(QString ip_port, QString msg)
{
    emit updateMsg(ip_port,msg);

}


void Server::updateMessage(QJsonObject json)
{
    emit updateMsg(json);
}


void Server::updateClients(QString address)
{
    emit updateClient(address);
}
void Server::writeMsgToClient(int sptr,QJsonObject json)
{
    qDebug()<<"writeMsgToClient";
    emit writeMsg(sptr,json);

}




//客户端断开连接时删除
void Server::deleteClientThread(DispatcherThread *pthread)
{

    for(int i = 0; i < m_threadList.count();i++)
    {
        DispatcherThread * dThread = m_threadList.at(i);
        if(dThread == pthread)
        {
            emit removeClient(dThread->getAddressIp());
            QString cip=dThread->getAddressIp();
            QStringList ip_subList=cip.split(":");
            QString ip=ip_subList[3];
            QString file=Constant::DataBasePath;
            Qt::HANDLE threadId = QThread::currentThreadId();
            QString threadIdStr = QString::number(reinterpret_cast<quintptr>(threadId));

            MySql *mySql = new MySql(file,threadIdStr);
            mySql->MyUpdateLoginState(ip,"0");
            delete mySql;
            dThread->wait();
            delete dThread;
            m_threadList.removeAt(i);
            qDebug()<<thread();
            qDebug()<<"delete thread OK";
            return;
        }
    }
}


